Dictionaries
Dictionaries
Introduction
A dictionary stores data as key-value pairs. Keys must be unique and are used to look up values. Dictionaries are unordered in older Python versions, but in Python 3.7+ they preserve insertion order.
Creating a Dictionary
employee = {
"firstname": "Alice",
"lastname": "Smith",
"department": "Engineering",
"salary": 80000
}
Accessing Values
print(employee["firstname"]) # Alice
print(employee.get("salary")) # 80000
print(employee.get("age", "unknown")) # unknown — default if key missing
Use
.get()when the key may not exist — accessing a missing key with[]raises aKeyError.
Adding and Updating
employee["age"] = 30 # add a new key
employee["salary"] = 85000 # update an existing key
Removing Items
employee.pop("age") # remove by key, returns the value
del employee["lastname"] # remove by key
Checking Keys
if "department" in employee:
print(employee["department"])